jclass={
	initPage:function(){
		// 绑定dom对象
		this.obj = {
			searchText:$('#searchText'),
		};
		// 声明全局变量
		this.data = {
            datatable:[],
            tableParams: {
                nickName: '',
                page:1,
                size:10
            },
            zTree: {},
            zNodes: [
                { id:55, pId:0, name:"随意勾选 1", open:true},
                { id:11, pId:10, name:"随意勾选 1-1", open:true},
                { id:111, pId:11, name:"随意勾选 1-1-1"},
                { id:112, pId:11, name:"随意勾选 1-1-2"},
                { id:12, pId:1, name:"随意勾选 1-2", open:true},
                { id:121, pId:12, name:"随意勾选 1-2-1"},
                { id:122, pId:12, name:"随意勾选 1-2-2"},
                { id:2, pId:0, name:"随意勾选 2", open:true},
                { id:21, pId:2, name:"随意勾选 2-1"},
                { id:22, pId:2, name:"随意勾选 2-2", open:true},
                { id:221, pId:22, name:"随意勾选 2-2-1"},
                { id:222, pId:22, name:"随意勾选 2-2-2"},
                { id:23, pId:2, name:"随意勾选 2-3"}
            ],
            addDialogParams: {
            	nickName: '',
            	areaName: '',
            	resourcesList: '',
            	roleMark: '',
            	description: ''
            }
        };
        this.getTableList();
        // this.creatTable();
        this.bindEvent();
        diquSelceted();
        this.initTree();
        // this.initTrees();
	},
    // jdtree 树型结构json
    initTree() {
        
        jrequest.get("/api/menus",{}).then(res => {
            let menu = res.data.menuItem
            let a = (data) => {
                data.forEach(item => {
                    item.code = item.id
                    delete item.id
                    item.disabled = false
                    item.isOpened = true
                    item.name = item.menuName
                    delete item.menuName
                    if (item.menuItem && item.menuItem.length > 0) {
                        item.hasChild = true
                        item.child = item.menuItem
                        delete item.menuItem
                        a(item.child)
                    } else {
                        item.hasChild = false
                    }
                })
            }
            a(menu)
            jdtree.init(menu)
            console.log(menu)
        })
    },
	// 弹框中的菜单权限tree
    initTrees(checkedstr) {
        
        checkedstr = checkedstr || ""
        let checkedarr = []
        if (checkedstr) checkedarr = checkedstr.split(",")
        $(".alarm-tree").hide()
        jrequest.get("/api/menu",{}).then(res => {
            // console.log(res)
            res.data.forEach(item => {
                item.open = true
                if (checkedarr) {
                    checkedarr.forEach(checkedcode => {
                        if (checkedcode == item.id) {
                        	item.checked = true
                        	// item.halfCheck = true
                        }
                    })
                }
                item.pId = item.pid
                item.types = item.level
            })
            // console.log(res.data)
            let that = this
            $.fn.zTree.init($("#treeDemo"), {
                view: {
                    showIcon: false,
                    showLine: false
                },
                check: {
                    enable: true
                },
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onCheck: (e, treeId, treeNode) => {
                        // let nodes = this.data.zTree.getChangeCheckedNodes();
                        let nodes = this.data.zTree.getCheckedNodes();
                        console.log(nodes)
                        let str = ''
                        let ids = ''
                        let idarr = []
                        nodes.forEach(item => {
                        	if (item.types === 6) {
                        		str += `${item.name},`
                            	ids += `${item.id},`
                                idarr.push(item.id)
                        	}
                        })
                        console.log(str)
                        console.log(ids.slice(0,-1))
                        // that.data.addDialogParams.resourcesList = ids.slice(0,-1)
                        that.data.addDialogParams.resourcesList = idarr
                    }
                }
            },res.data);
            this.setCheck();
        });
    },
    setCheck() {
        this.data.zTree = $.fn.zTree.getZTreeObj("treeDemo");
        this.data.zTree.setting.check.chkboxType = {Y: "s", N: "s"};
    },
	bindEvent() {
		$("#resetClick").click(() => {
            $("#input_search_name").val("")

            this.data.tableParams = {
                nickName: '',
                page:1,
                size:10
            }
        })
        $("#searchClick").click(() => {
            this.getTableList()
        })
        $("#btn_add_dialog").click(() => {
        	this.initTree()
        	// 可编辑
        	$("#ruleDialog").find("input").attr("disabled",false)
        	$("#ruleDialog").find("textarea").attr("disabled",false)
        	$("#add_dialog_submit").attr("disabled",false)
        	$("#qrm_input").removeClass("disable")
        	$("#treeDemo").removeClass("disable")

        	addDialog()
        })
        $("#add_dialog_submit").click(() => {
            this.data.addDialogParams.resourcesList = jdtree.getCheckLevel()
            console.log(this.data.addDialogParams.resourcesList,"222222222222222222222")
            if ($("#qrm_input").find("input").val()) {
            	if (this.data.addDialogParams.resourcesList.length > 0) {
	            	this.data.addDialogParams.areaName = $("#qrm_input").find("input").attr("data-id")
		            let dataform = $("#form_rule").serializeArray()
		            console.log(dataform)
		            let obj = {}
		            dataform.map((item,index) => {
		                obj[item.name] = item.value
		            })
		            console.log(obj)
		            if(obj.nickName) {
		            	this.data.addDialogParams.nickName = obj.nickName
						this.data.addDialogParams.roleMark = obj.roleMark
						this.data.addDialogParams.description = obj.description
						
		                this.addSubmit()
		                return false
		            }
	            } else {
	            	JPop.alert({msg:"请选择菜单"})
	            	return false
	            }
            } else {
				JPop.alert({msg:"请选择地区"})
				return false
            }
            
            
        })
	},
	addSubmit() {
		if (this.data.addDialogParams.id) {
            jrequest.put("/api/role",this.data.addDialogParams).then(res => {
                if(res) {
                    JPop.alert({msg:'修改成功！',type:'success'})
                    closeDialog()
                    this.getTableList()
                }
            })
        } else {
            jrequest.post("/api/role",this.data.addDialogParams).then(res => {
                if(res) {
                    JPop.alert({msg:'添加成功！',type:'success'})
                    closeDialog()
                    this.getTableList()
                }
            })
        }
	},
	getTableList() {
        $("#jid_loading").show()
        this.data.tableParams.nickName = $("#input_search_name").val()
        jrequest.get("/api/role",this.data.tableParams).then(res => {
            this.data.datatable = res.data
            var height = $(".table-con").height()-180;
            $('#jtable_rule').bootstrapTable('destroy');
            this.creatTable(res,height)
            // $("#jtable_rule").bootstrapTable('load',res.data);
            $("#jid_loading").hide()
        })
    },
	tableEvent:function(id,data,columns,paginationShow,total,height){
		data.forEach(item => {
            item.Button = this.operateFormatter()
        })
		let that = this
		$('#' + id).bootstrapTable({
            method: 'get',
            cache: false,
            height: 320,
            pagination: paginationShow,
            pageSize: that.data.tableParams.size,
            pageNumber:that.data.tableParams.page,
            showColumns: true,
            striped: true,
            columns: columns,
            sidePagination: 'server', // client or server
            totalRows: total,
            data :data,
            onPageChange: function (size, number) {
                console.log(number)
                that.data.tableParams.page = number
                that.data.tableParams.size = size
                that.getTableList()
            },
            formatNoMatches: function(){
                return '暂无数据';
            }
        });
	},
	creatTable:function(res,height){
        let self = this
		var columnsOne = [
            {
                title : '序号',
                align: "center",
                formatter: function (value, row, index) {
                    //获取每页显示的数量
                    var pageSize=self.data.tableParams.size;
                    //获取当前是第几页
                    var pageNumber=self.data.tableParams.page;
                    //返回序号，注意index是从0开始的，所以要加上1
                    return pageSize * (pageNumber - 1) + index + 1;
                }
            },
            {
                field: 'nickName',
                title: '角色名称'
            },
			{
				field: 'manageAreaName',
				title: '角色归属'
			},
			
			{
				field: 'description',
				title: '角色描述',
			},
			{
                field: 'Button',
                title: '操作',
                width: "200",
                align: 'center',
                events: operateEvents,
            }
		];
		this.tableEvent("jtable_rule",res.data,columnsOne,true,res.total,height);
	},
	operateFormatter() {
        return [
        	'<button type="button" id="table_gui">查看</button>',
            '<button type="button" id="table_edit">编辑</button>',
            '<button type="button" id="table_del">删除</button>'
            
        ].join('');
    }
}

$(function(){
	jclass.initPage();

	// 表格操作按钮
    window.operateEvents = {
        'click #table_edit': (e,value,row,index) => {
        	jrequest.get(`/api/role/${row.id}`,{}).then(res => {
        		// console.log(res.data)
        		let data = res.data
        		let cdstr = ''
        		data.resourcesList.forEach(item => {
        			cdstr += item + ','
        		})
                data.resourcesList = cdstr.slice(0,-1)
                jdtree.setChecked(data.resourcesList)
        		// jclass.initTree(data.resourcesList)
	        	$("#qrm_input").find("input").val(data.manageAreaName)
	        	$("#input_nikename").val(data.nickName)
	        	$("#input_mark").val(data.roleMark)
	        	$("#input_des").val(data.description)
	        	jclass.data.addDialogParams = data

	        	// 可编辑
	        	$("#ruleDialog").find("input").attr("disabled",false)
	        	$("#ruleDialog").find("textarea").attr("disabled",false)
	        	$("#add_dialog_submit").attr("disabled",false)
	        	$("#qrm_input").removeClass("disable")
	        	$("#jdul_tree").removeClass("disable")

	            addDialog()
        	})
        	
        },
        'click #table_gui': (e,value,row,index) => {
        	jrequest.get(`/api/role/${row.id}`,{}).then(res => {
        		// console.log(res.data)
        		let data = res.data
        		let cdstr = ''
        		data.resourcesList.forEach(item => {
        			cdstr += item + ','
        		})
        		data.resourcesList = cdstr.slice(0,-1)
                jdtree.setChecked(data.resourcesList)
        		// jclass.initTree(data.resourcesList)
	        	$("#qrm_input").find("input").val(data.manageAreaName)
	        	$("#input_nikename").val(data.nickName)
	        	$("#input_mark").val(data.roleMark)
	        	$("#input_des").val(data.description)

	        	// 查看 不可编辑
	        	$("#ruleDialog").find("input").attr("disabled",true)
	        	$("#ruleDialog").find("textarea").attr("disabled",true)
	        	$("#add_dialog_submit").attr("disabled",true)
	        	$("#qrm_input").addClass("disable")
	        	$("#jdul_tree").addClass("disable")

	            addDialog()
        	})
        	
        },
        'click #table_del': (e,value,row,index) => {
            JPop.dialogDel({msg:'确定删除?',operate:true}).on(success => {
                if (success) {
                    jrequest.delete(`/api/role/${row.id}`,{}).then(res => {
                        if (res) {
                            jclass.getTableList()
                        }
                    })
                }
            })
            // Jdialog.confirm({ message: `确定删除${row.nickName}?` }).on(function (e) {
            //     if (e) {
            //         jrequest.delete(`/api/role/${row.id}`,{}).then(res => {
            //             if (res) {
            //                 jclass.getTableList()
            //             }
            //         })
            //     }
            // });
        }
    }

	// $.fn.zTree.init($("#treeDemo"), setting, zNodes);
	// setCheck();

});

function addDialog() {
    $("#ruleDialog").show()
}
function closeDialog() {
	jclass.data.addDialogParams = {
		nickName: '',
    	areaName: '',
    	resourcesList: '',
    	roleMark: '',
    	description: ''
	}
	$("#ruleDialog").find("input").val("")
	$("#ruleDialog").find("textarea").val("")

	// $("#form_rule")[0].reset()
    $("#ruleDialog").hide()
}

/**
 * 请求地区数据
 * */
function diquSelceted() {
    var self = this;
    var mapurl = http + urls.diquSelceted;
    console.log(mapurl)
    jrequest.get("/api/assessMent/selectByArea",{}).then(res => {
        let data = res.data
        data[0].code = 1;
        $.each(data[0].cityAreaVOS, function(i, dom) {
            data[0].cityAreaVOS[i].code = 2;
            $.each(data[0].cityAreaVOS[i].cityAreaVOS, function(j, dom) {
                data[0].cityAreaVOS[i].cityAreaVOS[j].code = 3;
            })
        })
        creatMainRido("role_qrm_main", data, "cityAreaVOS", "code");
    })
}
/**
 * 下拉框
 * */
function creatMainRido(id, attr, child, jibie) {
    $(id).html("");
    var sttrdiv = "";
    for(var i = 0; i < 3; i++) {
        sttrdiv += "<div class='qrm-border" + (i + 1) + "' style='display:none'>" +
            "<ul class='qrm-lev-" + (i + 1) + " qrm-lev' id='qrm-border1'>" +
            "</ul>" +
            "</div>"
    };
    $(".qrm-main").html(sttrdiv);
    var str = "";
    $("#qrm-border1").html("");
    var forTree = function(o) {
        for(var i = 0; i < o.length; i++) {
            var urlstr = "";
            try {
                urlstr = "<li><span data-id='" + o[i]["id"] + "'>" + o[i]["name"] + "</span><i class='qrm-arrow-right'></i><ul class='li-zi-" + o[i][jibie] + "' style='display: none'>";
                str += urlstr;
                if(o[i][child] != null) {
                    forTree(o[i][child]);
                }
                str += "</ul>";
            } catch(e) {}
        }
        return str;
    };
    $("#qrm-border1").html(forTree(attr));
}


